package com.demo.demospringboot.controller;

import com.demo.demospringboot.dto.LoginRequest;
import com.demo.demospringboot.dto.LoginResponse;
import com.demo.demospringboot.dto.RegisterRequest;
import com.demo.demospringboot.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "*")

public class UserController {

  private static final Logger logger = LoggerFactory.getLogger(UserController.class);
  private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

  @Autowired
  private UserService userService;

  /**
   * 用户登录
   * POST /api/user/login
   */
  @PostMapping("/login")
  public LoginResponse login(@RequestBody LoginRequest loginRequest) {
    String requestId = generateRequestId();
    LocalDateTime startTime = LocalDateTime.now();

    logger.info("[{}] 开始处理用户登录请求 - 用户名: {}", requestId, loginRequest.getUsername());
    logger.debug("[{}] 登录请求参数: {}", requestId, loginRequest);

    try {
      LoginResponse response = userService.login(loginRequest);

      LocalDateTime endTime = LocalDateTime.now();
      long duration = java.time.Duration.between(startTime, endTime).toMillis();

      if (response.isSuccess()) {
        logger.info("[{}] 用户登录成功 - 用户名: {}, 耗时: {}ms",
            requestId, loginRequest.getUsername(), duration);
        logger.debug("[{}] 登录响应: {}", requestId, response);
      } else {
        logger.warn("[{}] 用户登录失败 - 用户名: {}, 原因: {}, 耗时: {}ms",
            requestId, loginRequest.getUsername(), response.getMessage(), duration);
      }

      return response;
    } catch (Exception e) {
      LocalDateTime endTime = LocalDateTime.now();
      long duration = java.time.Duration.between(startTime, endTime).toMillis();

      logger.error("[{}] 用户登录异常 - 用户名: {}, 异常: {}, 耗时: {}ms",
          requestId, loginRequest.getUsername(), e.getMessage(), duration, e);

      return LoginResponse.failure("系统异常，请稍后重试");
    }
  }

  /**
   * 用户注册
   * POST /api/user/register
   */
  @PostMapping("/register")
  public LoginResponse register(@RequestBody RegisterRequest registerRequest) {
    String requestId = generateRequestId();
    LocalDateTime startTime = LocalDateTime.now();

    logger.info("[{}] 开始处理用户注册请求 - 用户名: {}, 邮箱: {}",
        requestId, registerRequest.getUsername(), registerRequest.getEmail());
    logger.debug("[{}] 注册请求参数: {}", requestId, registerRequest);

    try {
      LoginResponse response = userService.register(registerRequest);

      LocalDateTime endTime = LocalDateTime.now();
      long duration = java.time.Duration.between(startTime, endTime).toMillis();

      if (response.isSuccess()) {
        logger.info("[{}] 用户注册成功 - 用户名: {}, 邮箱: {}, 耗时: {}ms",
            requestId, registerRequest.getUsername(), registerRequest.getEmail(), duration);
        logger.debug("[{}] 注册响应: {}", requestId, response);
      } else {
        logger.warn("[{}] 用户注册失败 - 用户名: {}, 邮箱: {}, 原因: {}, 耗时: {}ms",
            requestId, registerRequest.getUsername(), registerRequest.getEmail(),
            response.getMessage(), duration);
      }

      return response;
    } catch (Exception e) {
      LocalDateTime endTime = LocalDateTime.now();
      long duration = java.time.Duration.between(startTime, endTime).toMillis();

      logger.error("[{}] 用户注册异常 - 用户名: {}, 邮箱: {}, 异常: {}, 耗时: {}ms",
          requestId, registerRequest.getUsername(), registerRequest.getEmail(),
          e.getMessage(), duration, e);

      return LoginResponse.failure("系统异常，请稍后重试");
    }
  }

  /**
   * 测试接口
   * GET /api/user/test
   */
  @GetMapping("/test")
  public String test() {
    String requestId = generateRequestId();
    logger.info("[{}] 测试接口被调用", requestId);
    return "用户服务正常运行";
  }

  /**
   * 生成请求ID
   */
  private String generateRequestId() {
    return "REQ_" + System.currentTimeMillis() + "_" + Thread.currentThread().getId();
  }
}image.png